<?php

class usersOnline {

	var $timeout = 400;
	var $count = 0;
	var $error;
	var $i = 0;
	
	public function __construct () {
		$this->timestamp = time();
		$this->ip = $this->ipCheck();
		$this->new_user();
		$this->delete_user();
		$this->count_users();
	}
	
	function ipCheck() {
		if (getenv('HTTP_CLIENT_IP')) {
			$ip = getenv('HTTP_CLIENT_IP');
		}
		elseif (getenv('HTTP_X_FORWARDED_FOR')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_X_FORWARDED')) {
			$ip = getenv('HTTP_X_FORWARDED');
		}
		elseif (getenv('HTTP_FORWARDED_FOR')) {
			$ip = getenv('HTTP_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_FORWARDED')) {
			$ip = getenv('HTTP_FORWARDED');
		}
		else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		
		if(empty($ip)){
			$ip = '00.000.000.000';
		}
		
		return $ip;
	}
	
	function new_user() {
		$insert = $GLOBALS['db']->query("INSERT INTO {prefix}useronline(uid, timestamp, ip, logged, location) VALUES ('".intval($_SESSION['id'])."', '".$this->timestamp."', '".$this->ip."', '".intval($_SESSION['logged'])."', '".$_SESSION['location']."')");
		if (!$insert) {
			$this->error[$this->i] = "Unable to record new visitor\r\n";			
			$this->i ++;
		}
	}
	
	function delete_user() {
		$delete = $GLOBALS['db']->query("DELETE FROM {prefix}useronline WHERE timestamp < (".$this->timestamp." - ".$this->timeout.")");
		if (!$delete) {
			$this->error[$this->i] = "Unable to delete visitors";
			$this->i ++;
		}
	}
	
	function count_users() {
		if (count($this->error) == 0) {
			$query = $GLOBALS['db']->query("SELECT DISTINCT ip FROM {prefix}useronline");
			$count = (int)$query->num_rows;
			return $count;
		}
	}
	
	function count_logged_users() {
		if (count($this->error) == 0) {
			$query = $GLOBALS['db']->query("SELECT DISTINCT ip FROM {prefix}useronline WHERE logged = '1'");
			$count = (int)$query->num_rows;
			return $count;
		}
	}
	
	function count_users_component($com) {
		if (count($this->error) == 0) {
			$query = $GLOBALS['db']->query("SELECT DISTINCT ip FROM {prefix}useronline WHERE location LIKE '".$com."'") or exit($GLOBALS['db']->error());
			$count = (int)$query->num_rows;
			return $count;
		}
	}
	
	function count_logged_users_component($com) {
		if (count($this->error) == 0) {
			$query = $GLOBALS['db']->query("SELECT DISTINCT ip FROM {prefix}useronline WHERE location LIKE '".$com."' AND logged = '1'");
			$count = (int)$query->num_rows;
			return $count;
		}
	}
	
	function get_uid() {
		if (count($this->error) == 0) {
			$query = $GLOBALS['db']->query("SELECT DISTINCT uid FROM {prefix}useronline WHERE logged = '1'");
			return $query;
		}
	}

    function get_uid_component($com) {
		if (count($this->error) == 0) {
			$query = $GLOBALS['db']->query("SELECT DISTINCT uid FROM {prefix}useronline WHERE location LIKE '".$com."' AND logged = '1'");
			return $query;
		}
	}

}

?>